import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Select, Button, Card, message, Radio, Cascader, Upload, Icon, Modal } from 'antd';
import globalConstant from '../../utils/globalConstant';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

@connect(({ bussiness, general, loading }) => ({
  bussiness,
  general,
  loading: loading.models.bussiness,
}))
@Form.create()
export default class AddBusiness extends PureComponent {
  state = {
    uploadFileLength: [],
    previewVisible: false,
    previewImage: '',
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'general/getDistrictList',
    });
    dispatch({
      type: 'general/getProvincesList',
      payload: {
        maxLevel: 2,
      },
    });
    dispatch({
      type: 'general/getNetworkSpeedList',
      payload: {
        dictGroupCode: 'NETWORK_SPEED',
      },
    });
    dispatch({
      type: 'general/getNetworkOperatorList',
      payload: {
        dictGroupCode: 'NETWORK_OPERATOR_TYPE',
      },
    });
  }
  /*
    处理表单数据
   */
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({
          uploadFileLength: [],
        });
        const fileListArray = [];
        fileListArray.push(values.upload && values.upload.map(item => (
          item.response && item.response.data.map(items => items.fileUrl))));
        const networkSpeedArray = [];
        values.descendingSpeed.map((item) => {
          return networkSpeedArray.push({ networkSpeed: Number(item) });
        });
        console.log(fileListArray);
        this.props.dispatch({
          type: 'bussiness/add',
          payload: {
            networkOperatorType: values.networkOperator,
            bussinessPhoto: fileListArray[0] === undefined ? null : fileListArray[0][0][0].toString(),
            bussinessName: values.bussinessName,
            netSpeeds: networkSpeedArray,
            bussinessCityId: Number(values.cities[1]),
            networkProxyType: values.networkProxyType,
          },
          callback: () => {
            this.props.form.setFieldsValue({ upload: null });
            this.props.form.resetFields();
            this.props.handleAddModal(true);
          },
        });
      }
    });
  }
  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    this.setState({
      uploadFileLength: e.fileList,
    });
    return e && e.fileList;
  }
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  handleCancel=() => {
    this.setState({
      previewVisible: false,
    });
  }
  render() {
    const {
      general:
        {
          districtList,
          networkSpeedList,
          provincesList,
          networkOperatorList,
        },
    } = this.props;
    const { uploadFileLength, previewImage, previewVisible } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };
    const children = [];
    districtList.map(item => (
      children.push(
        <Select.Option
          key={item.id}
          value={item.id}
        >{item.districtName}
        </Select.Option>)
    ));
    const networkSpeed = [];
    networkSpeedList.map(item => (
      networkSpeed.push(
        <Select.Option
          key={item.dictItemName}
          value={item.dictItemName}
        >{item.dictItemName}M
        </Select.Option>)
    ));
    const networkOperatorArray = [];
    networkOperatorList.map(item => (
      networkOperatorArray.push(
        <Select.Option
          key={item.dictItemOrder}
          value={item.dictItemCode}
        >{item.dictItemName}
        </Select.Option>
      )
    ));

    const updateProps = {
      name: 'file',
      action: globalConstant.fileUploadURL,
      headers: {
        authorization: 'authorization-text',
      },
      listType: 'picture-card',
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} file uploaded successfully`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div >点击选择</div>
      </div>
    );
    return (
      <Card bordered={false}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem
            {...formItemLayout}
            label="运营商名称"
          >
            {getFieldDecorator('bussinessName', {
              rules: [
                {
                  required: true, message: '请输入运营商名称',
                }],
            })(
              <Input placeholder="请输入运营商名称" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="代理类型"
          >
            {getFieldDecorator('networkProxyType', {
              rules: [
                {
                  required: true, message: '请选择代理类型',
                }],
            })(
              <RadioGroup>
                <Radio value="NETWORK_PROXY_TYPE_SELF">自营</Radio>
                <Radio value="NETWORK_PROXY_TYPE_PROXY">代理</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="网络提供商"
            hasFeedback
          >
            {getFieldDecorator('networkOperator', {
              rules: [
                {
                  required: true, message: '请选择网络提供商',
                }],
            })(
              <Select
                style={{ width: '100%' }}
                placeholder="请选择下行网速"
              >
                {networkOperatorArray}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="下行网速"
            hasFeedback
          >
            {getFieldDecorator('descendingSpeed', {
              rules: [
                {
                  type: 'array',
                },
                {
                  required: true, message: '请选择下行网速',
                }],
            })(
              <Select
                mode="multiple"
                style={{ width: '100%' }}
                placeholder="请选择下行网速"
              >
                {networkSpeed}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="所属城市"
            hasFeedback
          >
            {getFieldDecorator('cities', {
              rules: [
                {
                  required: true, message: '请选择所属城市',
                }],
            })(
              <Cascader options={provincesList} placeholder="请选择所属城市" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="图片"
          >
            {getFieldDecorator('upload', {
              valuePropName: 'fileList',
              getValueFromEvent: this.normFile,
            })(
              <Upload {...updateProps} onPreview={this.handlePreview}>
                {uploadFileLength.length >= 1 ? null : uploadButton}
              </Upload>
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">保存</Button>
          </FormItem>
        </Form>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Card>
    );
  }
}
